import os

class logger(object):
    def __init__(self, opt):
        super().__init__()

        if hasattr(opt, "log_name"):
            self.name = opt.log_name
        else:
            self.name = "log_default"

        if not os.path.exists('log'):
            os.mkdir('log')
        
        self.fp = open('log/'+self.name+'.txt', 'w')

        initmsgs = opt._get_kwargs()
        self.append('###### arguments ######')
        self.append(initmsgs)
        self.append('#######################')

    def append(self, kwargs):
        if isinstance(kwargs, dict):
            msg = ""
            for key, value in kwargs.items():
                if type(value) == float:
                    value = round(value, 4)
                msg += f"{key} : {value}, "
        elif isinstance(kwargs, list):
            msg = ""
            for key, value in kwargs:
                if type(value) == float:
                    value = round(value, 4)
                msg += f"{key} : {value}, "
        else:
            msg = kwargs

        if msg[-1] != '\n':
            msg += '\n'
        self.fp.write(msg)

    def __del__(self):
        self.fp.close()